/*!
 * Ext JS Library 4.0
 * Copyright(c) 2006-2011 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */



var navWidth=215;
Ext.define('MyDesktop.GridWindow', {
    extend: 'Ext.ux.desktop.Module',

    requires: [
        'Ext.data.ArrayStore',
        'Ext.util.Format',
        'Ext.grid.Panel',
        'Ext.grid.RowNumberer',
        'Noter.models.Note',
        'Noter.models.Notetype',
        'Noter.stores.Notes',
        'Noter.stores.NotetypesTree',
        'Noter.view.NotetypeTree',
    ],

    id:'grid-win',

    init : function(){
        this.launcher = {
            text: 'Grid Window',
            iconCls:'icon-grid'
        };
    },

    createWindow : function(){
        var desktop = this.app.getDesktop();
        var win = desktop.getWindow('grid-win');
        if(!win){
            win = desktop.createWindow({
                id: 'grid-win',
                title:'Grid Window',
                width:740,
                height:480,
                iconCls: 'icon-grid',
                animCollapse:false,
                constrainHeader:true,
                layout:'border',
                defaults: {
                    collapsible: true,
                    split: true,
                    bodyStyle: 'padding:5px'
                },
                items: [ {
                            title: 'Navigation',
                            region:'west',
                            width: navWidth,
                            layout: 'fit',
                            border: false,
                            items: [{
                                    xtype :'notetypetree',
                                    store : new Noter.stores.NotetypesTree()
                            }], 
                        },{
                            title: 'Main Content',
                            collapsible: false,
                            region:'center',
                            margins: '5 0 0 0',
                            border: false,
                            items: MyDesktop.GridWindow.getGrid() 
                        }
                ],
            });
        }
        return win;
    },

    statics: {
        getGrid: function () {
            var store = new Noter.stores.Notes();

            var rowEditing = Ext.create('Ext.grid.plugin.RowEditing');

            var delAction = Ext.create('Ext.Action', {
                icon   : '../ext/examples/shared/icons/fam/delete.gif',  // Use a URL in the icon config
                text: 'Delete NT',
                disabled: true,
                handler: function(widget, event) {
                    var selection = grid.getView().getSelectionModel().getSelection()[0];
                    if (selection) {
                        store.remove(selection);
                    }
                }
            });
            var testAction = Ext.create('Ext.Action', {
                icon   : '../ext/examples/shared/icons/fam/delete.gif',  // Use a URL in the icon config
                text: 'Test',
                disabled: true,
                handler: function(widget, event) {
                    var selection = grid.getView().getSelectionModel().getSelection()[0];
                    //selection.data.ntname='xxxx';
                    store.save(selection);
                    console.log(selection.valueOf());

                    var win = MyDesktop.GridWindow.getEditWindow();
                    win.show();
                }
            });


            var contextMenu = Ext.create('Ext.menu.Menu', {
                items: [
                    delAction,
                    testAction
                ]
            });            
            
            var grid = Ext.create('Ext.grid.Panel', {
                plugins: [rowEditing],
                store: store,
                height: 300,
                iconCls: 'icon-user',
                columns: [{
                    text: 'ID',
                    width: 40,
                    sortable: true,
                    dataIndex: 'id'
                }, {
                    text: 'Name',
                    flex: 1,
                    sortable: true,
                    dataIndex: 'ntname',
                    field: {
                        xtype: 'textfield'
                    }
                }, {
                    header: 'Content',
                    sortable: true,
                    dataIndex: 'content',
                    field: {
                        xtype: 'textfield'
                    }
                }, {
                    header: 'Pid',
                    width: 80,
                    sortable: true,
                    dataIndex: 'pid',
                    field: {
                        xtype: 'textfield'
                    }
                }],
                bbar: Ext.create('Ext.PagingToolbar', {
                    store: store,
                    displayInfo: true,
                    //displayMsg: 'Displaying topics {0} - {1} of {2}',
                    //emptyMsg: "No topics to display",
                }),
                dockedItems: [{
                    xtype: 'toolbar',
                    items: [{
                        text: 'Add',
                        iconCls: 'add',
                        handler: function(){
                            store.insert(0, new Noter.models.Note());
                            rowEditing.startEdit(0, 0);
                        }
                    }, '-', {
                        itemId: 'delete',
                        text: 'Delete',
                        iconCls: 'remove',
                        disabled: true,
                        handler: function(){
                            var selection = grid.getView().getSelectionModel().getSelection()[0];
                            if (selection) {
                                store.remove(selection);
                            }
                        }
                    }]
                }],
                viewConfig: {
                    stripeRows: true,
                    listeners: {
                        itemcontextmenu: function(view, rec, node, index, e) {
                            e.stopEvent();
                            contextMenu.showAt(e.getXY());
                            return false;
                        }
                    }
                },                
            });

            grid.getSelectionModel().on('selectionchange', function(selModel, selections){
                grid.down('#delete').setDisabled(selections.length === 0);
                if (selections.length) {
                    delAction.enable();
                    testAction.enable();
                } else {
                    delAction.disable();
                    testAction.disable();
                }                
            });
            return grid;
        },

        getTGrid: function () {
            var store = Ext.create('Ext.data.Store', {
                autoLoad: true,
                autoSync: true,
                remoteSort: true,
                pageSize: 10,
                model: 'Noter.models.Notetype',
                proxy: {
                    type: 'rest',
                    url: '/notetype',
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'total'
                    },
                    writer: {
                        type: 'json'
                    }
                },
                listeners: {
                    write: function(store, operation){
                        var record = operation.getRecords()[0],
                            name = Ext.String.capitalize(operation.action),
                            verb;
                            
                        if (name == 'Destroy') {
                            record = operation.records[0];
                            verb = 'Destroyed';
                        } else {
                            verb = name + 'd';
                        }
                        console.log(name, Ext.String.format("{0} user: {1}", verb, record.getId()));
                    }
                }
            });
            
            var rowEditing = Ext.create('Ext.grid.plugin.RowEditing');

            var delAction = Ext.create('Ext.Action', {
                icon   : '../ext/examples/shared/icons/fam/delete.gif',  // Use a URL in the icon config
                text: 'Delete NT',
                disabled: true,
                handler: function(widget, event) {
                    var selection = grid.getView().getSelectionModel().getSelection()[0];
                    if (selection) {
                        store.remove(selection);
                    }
                }
            });
            var testAction = Ext.create('Ext.Action', {
                icon   : '../ext/examples/shared/icons/fam/delete.gif',  // Use a URL in the icon config
                text: 'Test',
                disabled: true,
                handler: function(widget, event) {
                    var selection = grid.getView().getSelectionModel().getSelection()[0];
                    selection.data.ntname='xxxx';
                    store.save(selection);
                    console.log(selection.valueOf());

                    var win = MyDesktop.GridWindow.getEditWindow();
                    win.show();
                }
            });


            var contextMenu = Ext.create('Ext.menu.Menu', {
                items: [
                    delAction,
                    testAction
                ]
            });            
            
            var grid = Ext.create('Ext.grid.Panel', {
                plugins: [rowEditing],
                store: store,
                height: 300,
                iconCls: 'icon-user',
                columns: [{
                    text: 'ID',
                    width: 40,
                    sortable: true,
                    dataIndex: 'id'
                }, {
                    text: 'Name',
                    flex: 1,
                    sortable: true,
                    dataIndex: 'ntname',
                    field: {
                        xtype: 'textfield'
                    }
                }, {
                    header: 'Pid',
                    width: 80,
                    sortable: true,
                    dataIndex: 'pid',
                    field: {
                        xtype: 'textfield'
                    }
                }],
                bbar: Ext.create('Ext.PagingToolbar', {
                    store: store,
                    displayInfo: true,
                    //displayMsg: 'Displaying topics {0} - {1} of {2}',
                    //emptyMsg: "No topics to display",
                }),
                dockedItems: [{
                    xtype: 'toolbar',
                    items: [{
                        text: 'Add',
                        iconCls: 'add',
                        handler: function(){
                            store.insert(0, new Noter.models.Notetype());
                            rowEditing.startEdit(0, 0);
                        }
                    }, '-', {
                        itemId: 'delete',
                        text: 'Delete',
                        iconCls: 'remove',
                        disabled: true,
                        handler: function(){
                            var selection = grid.getView().getSelectionModel().getSelection()[0];
                            if (selection) {
                                store.remove(selection);
                            }
                        }
                    }]
                }],
                viewConfig: {
                    stripeRows: true,
                    listeners: {
                        itemcontextmenu: function(view, rec, node, index, e) {
                            e.stopEvent();
                            contextMenu.showAt(e.getXY());
                            return false;
                        }
                    }
                },                
            });

            grid.getSelectionModel().on('selectionchange', function(selModel, selections){
                grid.down('#delete').setDisabled(selections.length === 0);
                if (selections.length) {
                    delAction.enable();
                    testAction.enable();
                } else {
                    delAction.disable();
                    testAction.disable();
                }                
            });
            return grid;
        },

        getEditWindow: function (){
                var descriptionHtmlEditor = new Ext.form.HtmlEditor({      
                    id:'dhtml',             
                    name: 'content',
                    allowBlank:true,
                    width:590,
                    height:450
                })
            
                var fpmu=new Ext.form.FormPanel({
                    border:false,
                    width:350,
                    frame:true,
                    autoHeight:true,
                    layout:'form',
                    border:false,
                    items:[descriptionHtmlEditor]
                })

                var win = new Ext.Window({
                    title : 'title',
                    closeAction : 'hide',
                    layout:'fit',
                    width : 750,
                    height : 360,
                    resizable : false,
                    modal : true,
                    items:[fpmu],
                    buttons:[ {
                        text:'submit',
                        handler:function(){
                            var f = fpmu.getForm();
                            Ext.Ajax.request({
                                url: '/note',
                                headers: {'Content-Type':'application/json; charset=utf-8'},
                                params: Ext.JSON.encode(f.getValues())
                            });
                        }
                    }]
                });
            return win;
        }
    }
});

